package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;




    @Autowired
    private AddressDao addressDao;

    @Override
    // 移动端的预约添加方法(微信预约)
    public Result order(Map map) throws Exception {
        //  检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);

        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null){
            // 日期为设置预约人数
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //  检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        if (orderSetting.getReservations() >= orderSetting.getNumber()){
           // 日期已经约满
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //  检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        
        if (member != null){
            // 当前用户是会员
            // 检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String) map.get("setmealId"));
            Order order = new Order(memberId,date,null,null,setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if (list !=null && list.size()>0){
                // 用户已预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }




        if (member == null){
            // 当前用户不是会员,需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        // 可以预约，更新套餐表的已预约人数
        orderSetting.setReservations(orderSetting.getReservations() +1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //5、预约成功，更新当日的已预约人数
        String address = (String) map.get("address");
        Integer addressId = addressDao.findIdByAddress(address);
        Order order = new Order();
        order.setAddressId(addressId);
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderDao.add(order);

        // 返回成功
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    // (移动端)根据id查询预约信息
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    // 分页查询(后台)
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Map<String,Object>> pages = orderDao.findPage(queryString);
        return new PageResult(pages.getTotal(),pages.getResult());
    }

    // 取消预约
    public void delete(Integer id) {
        orderDao.delete(id);
    }

    // 后台添加预约方法(电话预约)
    public Result add(Map map, Integer[] setmealIds) throws Exception {

        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);

        String phoneNumber = (String) map.get("phoneNumber");
        Member member = memberDao.findByTelephone(phoneNumber);

        if (member != null){
            // 当前用户是会员
            // 检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
            Integer memberId = member.getId();
            for (Integer setmealId : setmealIds) {
                Order order = new Order(memberId,date,null,null,setmealId);
                List<Order> list = orderDao.findByCondition(order);
                if (list !=null && list.size()>0){
                    // 用户已预约
                    return new Result(false,MessageConstant.HAS_ORDERED);
                }
            }
        }

        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        if (member == null){
            // 当前用户不是会员,需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(phoneNumber);
            member.setAge(Integer.parseInt((String) map.get("age")));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRemark((String) map.get("remark"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        // 预约表的添加
        for (Integer setmealId : setmealIds) {
            Order order = new Order(member.getId(),date,(String) map.get("orderType"),Order.ORDERSTATUS_NO,setmealId);
            orderDao.add(order);
        }

        // 返回成功
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }

}
